//
//  SingleSearchViewController.m
//  Feel_at_home
//
//  Created by 王静雨 on 15/9/24.
//  Copyright © 2015年 Feel_at_home. All rights reserved.
//

#import "SingleSearchViewController.h"
#import "SingleViewController.h"
#import "SingleModel.h"
#import "Singlecolltiongviecell.h"
#import <AFNetworking.h>
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
#import "SingleDetilsViewController.h"
#import "WidthAndHeight.pch"
#import "HTTPTOOL.h"

#define w self.view.frame.size.width
#define h self.view.frame.size.height


@interface SingleSearchViewController ()<UICollectionViewDataSource,UICollectionViewDelegate>

@property (nonatomic ,strong) UICollectionView *collectionView;
@property (nonatomic ,strong) NSMutableArray *arr;
@property (nonatomic ,strong) NSMutableDictionary *dic;
@property (nonatomic ,assign) NSInteger number;
@property (nonatomic ,assign) BOOL white;
@property (nonatomic ,strong) UISearchBar *searchBar;
@property (nonatomic ,strong) NSMutableArray *marr;


@end

@implementation SingleSearchViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self dataHandle];
    [self dataHandle1];
    
//    SingleViewController *single = [[SingleViewController alloc] init];
//    [self.navigationController pushViewController:single animated:YES];
    
    /* UICollectionViewLayout 布局累
     作用 ： 对cell进行布局（大小，位置 等信息）
     是布局的基类 ，通常使用其子类UICollectionViewFlowLayout创建对象
     */
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    /* 更改item 大小 默认（50 * 50） */
    flowLayout.itemSize = CGSizeMake(w / 2-20, w / 2 -20);
    
    /* 设置item 上下之间的距离（最小值）*/
    flowLayout.minimumLineSpacing = 10;
    
    /* 设置item 左右之间的距离（最小值） */
    flowLayout.minimumInteritemSpacing = 10;
    
    /* 设置距四边地距离 */
    flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    
    /* 创建对象 */
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, VCWIDTH, VCHEIGH +40) collectionViewLayout:flowLayout];
    /* 背景颜色默认是黑色 */
    
    /* 两个协议 */
    self.collectionView.delegate = self;
    self.collectionView.dataSource =self;
    [self.view addSubview:self.collectionView];
    
    self.collectionView.backgroundColor = [UIColor colorWithRed:0.948 green:1.000 blue:0.855 alpha:1.000];
    
    [self.collectionView registerClass:[Singlecolltiongviecell class] forCellWithReuseIdentifier:@"reuse1"];
    self.arr = [[NSMutableArray alloc]init];
    self.marr = [[NSMutableArray alloc] init];
    self.collectionView.header = [MJRefreshGifHeader headerWithRefreshingBlock:^{
        [self.collectionView.header beginRefreshing];
        self.number = 0;
        [self dataHandle];
    }];
    
    
    self.collectionView.footer = [MJRefreshAutoGifFooter footerWithRefreshingBlock:^{
        [self.collectionView.footer beginRefreshing];
        self.number +=20;
        
        [self dataHandle];
    }];

}

- (void)dataHandle
{

    NSString *urlString = [self.search stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    NSString *url = [NSString stringWithFormat:@SingleSearchUrl, urlString, self.number];

    [HTTPTOOL GETWithURL:url body:nil httpHead:nil responseStyle:JSON success:^(id result) {
//        NSMutableArray *array = [NSMutableArray array];
        
      NSMutableArray *array = [[result objectForKey:@"data"] objectForKey:@"items"];
        
        
        for (NSDictionary *dic in array) {
            SingleModel *model = [[SingleModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [self.arr addObject:model];
            
        }
        if(self.arr.count == 0)
        {
            
            // 判断手机系统版本
            NSString* phoneVersion = [[UIDevice currentDevice] systemVersion];
            NSLog(@"手机系统版本: %@", phoneVersion);
            NSLog(@"%ld", (long)phoneVersion.integerValue);
            if (phoneVersion.integerValue >= 8) {
                
                UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"啥也没找到哎！！" preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
                    //                    [self.navigationController popToRootViewControllerAnimated:YES];
                    
                }];
                
                [alert addAction:action1];
                
                [self presentViewController:alert animated:YES completion:^{
                    
                }];
                
            } else {
                
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"啥也没找到哎！！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
                [alert show];
                
            }
        }

        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        
    } fail:^(NSError *error) {
        
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
    }];
    
    
}



- (void)dataHandle1
{
    NSString *url = [NSString stringWithFormat:@SingleSearchToeUrl,
                     self.number];
    
    [HTTPTOOL GETWithURL:url body:nil httpHead:nil responseStyle:JSON
                 success:^(id result) {
     NSMutableArray *array = [[NSMutableArray alloc]init];
     array = [[result objectForKey:@"data"] objectForKey:@"items"];
                     
       for (NSDictionary *dic in array) {
            NSDictionary *datadic = [dic objectForKey:@"data"];
            SingleModel *model = [[SingleModel alloc]init];
            [model setValuesForKeysWithDictionary:datadic];
            [self.marr addObject:model];
                
         }
            [self.collectionView reloadData];
            [self.collectionView.header endRefreshing];
            [self.collectionView.footer endRefreshing];
                     
    } fail:^(NSError *error) {
        [self.collectionView reloadData];
        [self.collectionView.header endRefreshing];
        [self.collectionView.footer endRefreshing];
        
    }];
    
}



- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.arr.count;
    
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    Singlecolltiongviecell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse1" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor colorWithRed:0.938 green:1.000 blue:0.674 alpha:0.600];
    SingleModel *model = [self.arr objectAtIndex:indexPath.row];
    NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:model.name];
    NSRange range = [model.name rangeOfString:self.search];
    [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.name.attributedText = attributedString;

//    cell.name.text = model.name;
    cell.price.text = [NSString stringWithFormat:@"%@￥",model.price];
    [cell.imageview sd_setImageWithURL:[NSURL URLWithString:model.cover_image_url]];
    
    return cell;
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SingleDetilsViewController *singleDetai = [[SingleDetilsViewController alloc] init];
    [self.navigationController pushViewController:singleDetai animated:YES];
    SingleModel *model = [self.marr objectAtIndex:indexPath.row];
    singleDetai.myid = model.url;
//    singleDetai.myid = model.id;
    NSLog(@"^^^^^^^^^%@",model.id);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
